import re
import win32print


def get_system_printers():
    """获取系统安装的所有打印机及其信息"""
    printers = []
    try:
        system_printers = win32print.EnumPrinters(
            win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS,
            None,
            2,  # level=2，包含详细信息
        )
        for printer in system_printers:
            name = printer.get("pPrinterName")
            port_name = printer.get("pPortName")
            status_code = printer.get("Status")

            # 尝试从端口名解析IP地址
            ip_match = re.search(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", port_name)
            ip = ip_match.group(0) if ip_match else "N/A"

            status = parse_printer_status(status_code)
            printers.append({"name": name, "ip": ip, "status": status})

        print(f"成功获取到 {len(printers)} 台系统打印机。")
    except Exception as e:
        print(f"获取系统打印机列表失败: {e}")
    return printers


def parse_printer_status(status_code):
    """解析打印机状态码为可读文本"""
    if status_code == 0:
        return "就绪"
    status_map = {
        win32print.PRINTER_STATUS_BUSY: "繁忙",
        win32print.PRINTER_STATUS_DOOR_OPEN: "门被打开",
        win32print.PRINTER_STATUS_ERROR: "错误",
        win32print.PRINTER_STATUS_INITIALIZING: "正在初始化",
        win32print.PRINTER_STATUS_IO_ACTIVE: "I/O激活",
        win32print.PRINTER_STATUS_MANUAL_FEED: "手动进纸",
        win32print.PRINTER_STATUS_NO_TONER: "墨粉不足",
        win32print.PRINTER_STATUS_NOT_AVAILABLE: "不可用",
        win32print.PRINTER_STATUS_OFFLINE: "离线",
        win32print.PRINTER_STATUS_OUT_OF_MEMORY: "内存不足",
        win32print.PRINTER_STATUS_OUTPUT_BIN_FULL: "输出纸盒已满",
        win32print.PRINTER_STATUS_PAGE_PUNT: "页面无法打印",
        win32print.PRINTER_STATUS_PAPER_JAM: "卡纸",
        win32print.PRINTER_STATUS_PAPER_OUT: "缺纸",
        win32print.PRINTER_STATUS_PAPER_PROBLEM: "纸张问题",
        win32print.PRINTER_STATUS_PAUSED: "已暂停",
        win32print.PRINTER_STATUS_PENDING_DELETION: "等待删除",
        win32print.PRINTER_STATUS_PRINTING: "正在打印",
        win32print.PRINTER_STATUS_PROCESSING: "正在处理",
        win32print.PRINTER_STATUS_TONER_LOW: "墨粉少",
        win32print.PRINTER_STATUS_USER_INTERVENTION: "需要用户干预",
        win32print.PRINTER_STATUS_WAITING: "等待中",
        win32print.PRINTER_STATUS_WARMING_UP: "正在预热",
    }
    status_text = [text for code, text in status_map.items() if status_code & code]
    return ", ".join(status_text) if status_text else "未知状态"


print(get_system_printers())
